package ClassicDataStructuresAndAlgorithms.ClassicLinkedListAlgorithms;

public class Solution92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || head.next == null){
            return head;
        }

        ListNode pre = null;
        ListNode cur = head;
        ListNode nxt = head.next;

        //cur指向left元素
        int count = left;
        while (count-1 > 0){
            pre = cur;
            cur = nxt;
            if (nxt!=null){
                nxt = nxt.next;
            }
            count--;
        }

        ListNode startPre = null;
        if (pre != null){
            //如果pre不为null，则把pre赋值给前驱
            startPre = pre;
        }

        ListNode start = cur;
        //pre重新置空，为了后面反转的操作
        pre = null;

        int k = (right-left+1);

        while(k>0){
            cur.next = pre;
            pre = cur;
            cur = nxt;
            if (nxt!=null){
                nxt = nxt.next;
            }
            k--;
        }

        //此时cur指向right元素的下一个元素
        start.next = cur;
        if (startPre!=null){
            startPre.next = pre;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);

        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = null;

        Solution92 solution92 = new Solution92();
        solution92.reverseBetween(n1,2,4);
    }
}
